import { defineStore } from 'pinia'
import router from '@/router'

export const useViewTagsStore = defineStore('viewTags', {
	state: () => ({
		viewTags: []
	}),
	
	getters: {
		// 获取所有标签
		getViewTags: (state) => state.viewTags,
		
		// 获取标签数量
		getViewTagsCount: (state) => state.viewTags.length,
		
		// 根据路径查找标签
		findTagByPath: (state) => (fullPath) => {
			return state.viewTags.find(item => item.fullPath === fullPath)
		}
	},
	
	actions: {
		// 添加标签
		pushViewTags(route) {
			const backPathIndex = this.viewTags.findIndex(item => 
				item.fullPath == router.options.history.state.back
			)
			const target = this.viewTags.find(item => item.fullPath === route.fullPath)
			const isName = route.name
			
			if (!target && isName) {
				if (backPathIndex == -1) {
					this.viewTags.push(route)
				} else {
					this.viewTags.splice(backPathIndex + 1, 0, route)
				}
			}
		},
		
		// 移除标签
		removeViewTags(route) {
			this.viewTags.forEach((item, index) => {
				if (item.fullPath === route.fullPath) {
					this.viewTags.splice(index, 1)
				}
			})
		},
		
		// 更新标签
		updateViewTags(route) {
			this.viewTags.forEach((item) => {
				if (item.fullPath == route.fullPath) {
					Object.assign(item, route)
				}
			})
		},
		
		// 更新标签标题
		updateViewTagsTitle(title = '') {
			const nowFullPath = location.hash.substring(1)
			this.viewTags.forEach((item) => {
				if (item.fullPath == nowFullPath) {
					item.meta.title = title
				}
			})
		},
		
		// 清空所有标签
		clearViewTags() {
			this.viewTags = []
		}
	}
})